//
//  YBSignInReturnContentViewController.m
//  GongXinDangJian
//
//  Created by apple on 17/12/7.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YBSignInReturnContentViewController.h"
#import "XLChannelView.h"
#import "XLChannelItem.h"
#import "XLChannelHeader.h"
#import "LCustomAlertView.h"
#import "YBNormalShadowInputView.h"

#define HEADID @"XLChannelHeader"
#define ITEMID @"XLChannelItem"

@interface YBSignInReturnContentViewController ()<UICollectionViewDelegate , UICollectionViewDataSource , XLChannelViewDelegate , LCustomAlertDelegate , YBNormalShadowInputViewDelegate>
/**  back  */
@property (strong, nonatomic) UIScrollView  *backScrollView;

@property (nonatomic , strong) XLChannelView * selectView;

@property (nonatomic , strong) UICollectionView * collectionView;

@property (nonatomic , strong) NSMutableArray<YBMeetingReturnHeadModel *> * dataArray;

@property (nonatomic , strong) JCAlertView * jcAlertView;

@property (nonatomic , strong) UIButton * sureButton;

@property (nonatomic , assign) NSInteger currentDeleteIndex;

@property (nonatomic , strong) YBNormalShadowInputView * itemInputView;
@end

@implementation YBSignInReturnContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titlelabel.text = @"报名回执内容";
    self.currentDeleteIndex = 0;
    self.dataArray = [NSMutableArray array];
    [self ybInitUserInterface];
    [self ybInitDataSource];
}


-(void)ybInitUserInterface{
    
    [self.view addSubview:self.backScrollView];
    
    [self.backScrollView addSubview:self.selectView];
    
    [self.backScrollView addSubview:self.collectionView];
    
    [self.backScrollView addSubview:self.sureButton];
    
    self.collectionView.sd_layout.leftSpaceToView(self.backScrollView , 0).topSpaceToView(self.selectView , ItemHeight * 20).widthIs([UIScreen zj_screenWith]).heightIs(ItemHeight * 100);
    
    self.sureButton.sd_layout.leftSpaceToView(self.backScrollView , ItemWidth * 150).topSpaceToView(self.collectionView , ItemHeight * 20).widthIs([UIScreen zj_screenWith] - ItemWidth * 300).heightIs(ItemHeight * 100);
    
    [self.backScrollView setupAutoContentSizeWithBottomView:self.sureButton bottomMargin:ItemHeight * 50];
    
    [self.view addSubview:self.itemInputView];
}


-(void)ybInitDataSource{
    [YJProgressHUD showMessage:@"加载中..." duration:10 view:[UIApplication sharedApplication].keyWindow];
    [YBRequestManager request_meetingReturnItemListWithSuccessBlock:^(id object) {
        [YJProgressHUD hide];
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            NSMutableArray * theTempArray = [object[@"children"] mutableCopy];
            NSMutableArray * tempChildArray = [@[@{@"CODE_NAME" : @"添加" , @"CODE_GROUP" : @"回执单选项" , @"REMARK" : @"" , @"CODE_VALUE" : @"tj" , @"FID" : @"" , @"TYPE" : @"0" , @"ID" : [ToolClass createUUIDString] , @"SORT" : @""}] mutableCopy];
            
            [theTempArray addObject:[@{@"CODE_NAME" : @"自定义信息" , @"CODE_GROUP" : @"回执单选项" , @"REMARK" : @"" , @"CODE_VALUE" : @"zdyxx" , @"FID" : @"0" , @"TYPE" : @"-1" , @"ID" : [ToolClass createUUIDString] , @"SORT" : @"" , @"children" : tempChildArray} mutableCopy]];
            
            self.dataArray = [[NSArray yy_modelArrayWithClass:[YBMeetingReturnHeadModel class] json:theTempArray] mutableCopy];
            
            if (self.currentDiyArray.count > 0) {
                NSMutableIndexSet *idxSet = [[NSMutableIndexSet alloc] init];
                [idxSet addIndexesInRange:NSMakeRange(0, self.currentDiyArray.count)];
                [self.dataArray.lastObject.children insertObjects:self.currentDiyArray atIndexes:idxSet];
            }
            if (self.currentSelectArray.count > 0) {
                [self reSetSelectData];
            }
            [self calculateCollectionViewFrame];
            [self.collectionView reloadData];
            [self reloadSelectViewDataSourceWithSelectArray];
        }
    } failBlock:^(id object) {
        [YJProgressHUD hide];
        [YJProgressHUD showSuccess:@"网络错误" inview:self.view];
    }];
}

-(void)reSetSelectData{
    NSMutableArray * tempIDArray = [NSMutableArray array];
    for (YBMeetingReturnItemModel * model in self.currentSelectArray) {
        [tempIDArray addObject:model.ID];
    }
    NSMutableArray * tempDataArray = [self.dataArray mutableCopy];
    for (int k = 0 ; k < tempDataArray.count ; k ++) {
        YBMeetingReturnHeadModel * headModel = tempDataArray[k];
        for (int j = 0 ; j < headModel.children.count ; j ++) {
            YBMeetingReturnItemModel * itemModel = headModel.children[j];
            if ([tempIDArray containsObject:itemModel.ID]) {
                for (int i = 0 ; i < self.currentSelectArray.count ; i ++) {
                    if ([self.currentSelectArray[i].ID isEqualToString:itemModel.ID]) {
                        self.currentSelectArray[i].isSelected = YES;
                        [self.dataArray[k].children replaceObjectAtIndex:j withObject:self.currentSelectArray[i]];
                    }
                }
            }
        }
    }
}


-(void)option_sureButton:(UIButton *)sender{
    if (self.currentSelectArray.count == 0) {
        [YJProgressHUD showSuccess:@"请选择回执内容" inview:self.view];
        return;
    }
    [YJProgressHUD showMessage:@"确认中..." duration:10 view:[UIApplication sharedApplication].keyWindow];
    NSMutableArray * tempArray = [NSMutableArray array];
    for (YBMeetingReturnItemModel * model in self.currentSelectArray) {
        [tempArray addObject:@{@"ATTR_NAME" : [ToolClass returnNoNullStringWithString:model.CODE_NAME] , @"ATTR_COLUMN_NAME" : [ToolClass returnNoNullStringWithString:model.CODE_VALUE] ,@"ATTR_TYPE" : [ToolClass returnNoNullStringWithString:model.TYPE]}];
    }
    [YBRequestManager request_createReturnCardWithActId:self.ACTID attrs:[tempArray copy] successBlock:^(id object) {
        [YJProgressHUD hide];
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(didCreateReturnCardWithSelectArray: diyArray:)]) {
                [self.dataArray.lastObject.children removeLastObject];
                NSArray * diyArray = [self.dataArray.lastObject.children copy];
                [self.delegate didCreateReturnCardWithSelectArray:[self.currentSelectArray copy] diyArray:diyArray];
            }
            [YJProgressHUD showSuccess:@"创建成功" inview:self.view];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        else{
            [YJProgressHUD showSuccess:@"创建失败" inview:self.view];
        }
    } failBlock:^(id object) {
        [YJProgressHUD hide];
        [YJProgressHUD showSuccess:@"网络错误" inview:self.view];
    }];
}



-(void)calculateCollectionViewFrame{
    CGFloat headHeight = ItemHeight * 100 * self.dataArray.count;
    CGFloat theItemHeight = 0.f;
    for (YBMeetingReturnHeadModel * model in self.dataArray) {
        NSInteger lineCount = 0;
        if (model.children.count > 0) {
            lineCount = (model.children.count - 1) / 3 + 1;
            theItemHeight += lineCount * ItemHeight * 60 + (lineCount - 1) * ItemHeight * 20;
        }
        else{
            theItemHeight += ItemHeight * 40;
        }
    }
    self.collectionView.sd_layout.leftSpaceToView(self.backScrollView , 0).topSpaceToView(self.selectView , ItemHeight * 20).widthIs([UIScreen zj_screenWith]).heightIs(headHeight + theItemHeight);
    [self.collectionView updateLayout];
}


-(void)reloadSelectViewDataSourceWithSelectArray{
    NSInteger lineCount = 0;
    if (self.currentSelectArray.count > 0) {
        lineCount = (self.currentSelectArray.count - 1) / 3 + 1;
    }
    CGFloat intervalHeight = 0.f;
    if (lineCount == 0) {
        intervalHeight = 0.f;
    }
    else{
        intervalHeight = (lineCount - 1) * ItemHeight * 20;
    }
    self.selectView.frame = CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 200 + lineCount * ItemHeight * 60 + intervalHeight);
    [self.selectView changeDataSourceWithArray:self.currentSelectArray];
}


#pragma mark CollectionViewDelegate&DataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray[section].children.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.dataArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    XLChannelHeader * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADID forIndexPath:indexPath];
    headerView.model = self.dataArray[indexPath.section];
    return headerView;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XLChannelItem * item = [collectionView dequeueReusableCellWithReuseIdentifier:ITEMID forIndexPath:indexPath];
    item.model = self.dataArray[indexPath.section].children[indexPath.row];
    item.isFixed = YES;
    return  item;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    YBMeetingReturnItemModel * model = self.dataArray[indexPath.section].children[indexPath.row];
    if ([model.CODE_NAME isEqualToString:@"添加"]) {
        self.itemInputView.hidden = NO;
        [self.itemInputView.inputTextField becomeFirstResponder];
    }
    else{
        if (!model.isSelected) {
            model.isSelected = YES;
            [self.currentSelectArray addObject:model];
            XLChannelItem * item = (XLChannelItem *)[collectionView cellForItemAtIndexPath:indexPath];
            item.model = model;
            [self reloadSelectViewDataSourceWithSelectArray];
        }
        else{
            [YJProgressHUD showSuccess:@"已经添加啦" inview:self.view];
        }
    }
}


-(void)didClickDeleteButtonWithIndex:(NSInteger)index
{
    self.currentDeleteIndex = index;
    YBMeetingReturnItemModel * tempModel = self.currentSelectArray[index];
    LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:self.view.bounds alertMessage:[NSString stringWithFormat:@"是否删除 %@" , [ToolClass returnNoNullStringWithString:tempModel.CODE_NAME]] titlesArray:@[@"取消",@"确定"]];
    alert.delegate = self;
    self.jcAlertView = [[JCAlertView alloc]initWithCustomView:alert dismissWhenTouchedBackground:YES];
    [self.jcAlertView show];
}

#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    if (index == 1) {
        /**  确认  */
        YBMeetingReturnItemModel * tempModel = self.currentSelectArray[self.currentDeleteIndex];
        tempModel.isSelected = NO;
        [self.currentSelectArray removeObjectAtIndex:self.currentDeleteIndex];
        [self.collectionView reloadData];
        [self reloadSelectViewDataSourceWithSelectArray];
    }
    [self.jcAlertView dismissWithCompletion:nil];
}


-(void)ybNormalShadowInputViewDidClickWithName:(NSString *)name
{
    YBMeetingReturnHeadModel * tempHeadModel = nil;
    for (YBMeetingReturnHeadModel * headModel in self.dataArray) {
        if ([headModel.CODE_NAME isEqualToString:@"自定义信息"]) {
            tempHeadModel = headModel;
        }
        for (YBMeetingReturnItemModel * itemModel in headModel.children) {
            if ([itemModel.CODE_NAME isEqualToString:name]) {
                [YJProgressHUD showSuccess:@"已存在该标签" inview:[UIApplication sharedApplication].keyWindow];
                return;
            }
        }
    }
    NSDictionary * tempDic = @{@"CODE_NAME" : name , @"CODE_GROUP" : @"回执单选项" , @"REMARK" : @"" , @"CODE_VALUE" : [ToolClass transformToPinyinFirstWithString:name] , @"FID" : @"" , @"TYPE" : @"0" , @"ID" : [ToolClass createUUIDString] , @"SORT" : @""};
    [tempHeadModel.children insertObject:[YBMeetingReturnItemModel yy_modelWithDictionary:tempDic] atIndex:0];
    [self calculateCollectionViewFrame];
    [self.collectionView reloadData];
}




-(XLChannelView *)selectView
{
    if (!_selectView) {
        _selectView = [[XLChannelView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 200)];
        _selectView.delegate = self;
    }
    return _selectView;
}


- (UIScrollView *)backScrollView{
    if (!_backScrollView ) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0 , navHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - navHeight)];
        _backScrollView.showsVerticalScrollIndicator = NO;
        _backScrollView.showsHorizontalScrollIndicator = NO;
        _backScrollView.contentSize = _backScrollView.size;
        _backScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _backScrollView;
    
}


-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        CGFloat CellMarginX = [UIScreen zj_screenWScale] * 15;
        CGFloat CellMarginY = [UIScreen zj_screenHScale] * 10;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat cellWidth = ([UIScreen zj_screenWith] - 4 * CellMarginX)/3;
        flowLayout.itemSize = CGSizeMake(cellWidth,ItemHeight * 60);
        flowLayout.sectionInset = UIEdgeInsetsMake(CellMarginY, CellMarginX, CellMarginY, CellMarginX);
        flowLayout.minimumLineSpacing = CellMarginY;
        flowLayout.minimumInteritemSpacing = 1;
        flowLayout.headerReferenceSize = CGSizeMake([UIScreen zj_screenWith], ItemHeight * 60);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 100) collectionViewLayout:flowLayout];
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.showsVerticalScrollIndicator = false;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[XLChannelItem class] forCellWithReuseIdentifier:ITEMID];
        [_collectionView registerClass:[XLChannelHeader class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADID];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
    }
    return _collectionView;
}


-(NSMutableArray<YBMeetingReturnItemModel *> *)currentSelectArray
{
    if (!_currentSelectArray) {
        _currentSelectArray = [NSMutableArray array];
    }
    return _currentSelectArray;
}


-(UIButton *)sureButton
{
    if (!_sureButton) {
        _sureButton = [ToolClass createButtonWithFrame:CGRectMake(0, 0, 1, 1) text:@"确认" textColor:[UIColor whiteColor] imageName:@"" font:18];
        _sureButton.backgroundColor = [UIColor themeColor];
        _sureButton.clipsToBounds = YES;
        _sureButton.layer.cornerRadius = normalCornerRadius;
        [_sureButton addTarget:self action:@selector(option_sureButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureButton;
}


-(YBNormalShadowInputView *)itemInputView
{
    if (!_itemInputView) {
        _itemInputView = [[YBNormalShadowInputView alloc]initWithTitle:@"自定义"];
        _itemInputView.maxLength = 7;
        _itemInputView.noticeString = @"请输入自定义内容";
        _itemInputView.hidden = YES;
        _itemInputView.delegate = self;
    }
    return _itemInputView;
}

@end
